package com.quectel.core.module.partybuildingsurvey.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.google.common.base.Preconditions;
import com.quectel.constant.core.partybuilding.PartySurveyConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partybuildingsurvey.dao.PartySurveyDao;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyPersonBindingDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyQuestionDto;
import com.quectel.core.module.partybuildingsurvey.entity.PartySurveyEntity;
import com.quectel.core.module.partybuildingsurvey.service.*;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:38
 */
@DubboService
public class PartySurveyServiceImpl implements PartySurveyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartySurveyServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_SURVEY_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_SURVEY_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartySurveyDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_SURVEY_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartySurveyDao partySurveyDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private PartyPersonService partyPersonService;
    @Autowired
    private PartySurveyPersonBindingService partySurveyPersonBindingService;
    @Autowired
    private PartySurveyQuestionService partySurveyQuestionService;
    @Autowired
    private PartySurveyAnswerService partySurveyAnswerService;
    @Autowired
    private PartySurveyPersonAnswerService partySurveyPersonAnswerService;




    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @Lock(
            lockExpresses = {
                    RedisLockConstants.PARTY_SURVEY_LOCK + "#{#partySurveyDto.id}"
            }
    )
    public Long saveOrUpdate(PartySurveyDto partySurveyDto) {
        //提醒时间
        if(PartySurveyConstants.RemindType.NOT_REMIND.getType().equals(partySurveyDto.getRemindType())){
            partySurveyDto.setNotifyStatus(SystemConstants.YES);
        }else{
            PartySurveyConstants.RemindType byType = PartySurveyConstants.RemindType.getByType(partySurveyDto.getRemindType());
            Preconditions.checkNotNull(byType);
            DateTime dateTime = DateUtil.offsetMinute(partySurveyDto.getStartTime(), -byType.getMinute());
            partySurveyDto.setRemindTime(dateTime);
            partySurveyDto.setNotifyStatus(SystemConstants.NO);
        }


        if (partySurveyDto.getId() == null) {
            Long id = save(partySurveyDto);
            partySurveyDto.setId(id);
        } else {
            updateById(partySurveyDto);
        }

        // 删除绑定关系
        partySurveyPersonBindingService.deleteBySurveyId(partySurveyDto.getId());
        // 删除题目绑定关系
        partySurveyQuestionService.deleteBySurveyId(partySurveyDto.getId());


        if(CollectionUtils.isNotEmpty(partySurveyDto.getBindPerson())){
            // 绑定下党员信息到中间表
            for (PartySurveyPersonBindingDto bindingDto : partySurveyDto.getBindPerson()) {
                bindingDto.setPartySurveyId(partySurveyDto.getId());
                bindingDto.setCategory(partySurveyDto.getCategory());
                bindingDto.setAnonymous(SystemConstants.NO);
                partySurveyPersonBindingService.save(bindingDto);
            }
        }

        if(CollectionUtils.isNotEmpty(partySurveyDto.getBindQuestion())){
            //绑定题目到中间表
            for (PartySurveyQuestionDto questionDto : partySurveyDto.getBindQuestion()) {
                questionDto.setPartySurveyId(partySurveyDto.getId());
                //如果是多选 则保存对应的配置
                if(PartySurveyConstants.QuestionType.MULTIPLE_CHOICE.getType().equals(questionDto.getType()) || PartySurveyConstants.QuestionType.PIC_MULTIPLE_CHOICE.getType().equals(questionDto.getType())){
                    questionDto.setCustomAttr(JacksonUtils.toJsonString(questionDto.getMultipleConfig()));
                }

                partySurveyQuestionService.saveOrUpdate(questionDto);

            }
        }

        return partySurveyDto.getId();
    }


    @Override
    public PartySurveyDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_SURVEY_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartySurveyDto selectById(Long id) {
        PartySurveyEntity entity = partySurveyDao.selectById(id);
        PartySurveyDto partySurveyDto = paddingField(CopyUtils.copyObj(entity, PartySurveyDto.class));

        if(partySurveyDto!=null){
            List<PartySurveyQuestionDto> partySurveyQuestionDtos = partySurveyQuestionService.selectBySurveyId(id);
            partySurveyDto.setBindQuestion( partySurveyQuestionDtos.stream().sorted(Comparator.comparing(PartySurveyQuestionDto::getSort)).collect(Collectors.toList()));
        }


        return partySurveyDto;
    }

    @Override
    public List<PartySurveyDto> queryList(Map<String, Object> params) {
        List<PartySurveyEntity> list = partySurveyDao.queryList(params);
        List<PartySurveyDto> result = CopyUtils.copyList(list, PartySurveyDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartySurveyDto paddingField(PartySurveyDto dto) {
        if (dto != null) {

            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
            if (partyOrganizationDto != null) {
                dto.setPartyName(partyOrganizationDto.getName());
            }

            Map<String,Object> params = new HashMap<>();
            params.put(LambdaUtil.getFieldName(PartySurveyPersonBindingDto::getPartySurveyId),dto.getId());
            params.put(LambdaUtil.getFieldName(PartySurveyPersonBindingDto::getParticipateStatus),SystemConstants.YES);
            dto.setParticipateCount(partySurveyPersonBindingService.queryTotal(params));

            List<PartySurveyPersonBindingDto> partySurveyPersonBindingDtos = partySurveyPersonBindingService.selectBySurveyId(dto.getId());
            if(CollectionUtils.isNotEmpty(partySurveyPersonBindingDtos)){
                dto.setTotalCount(partySurveyPersonBindingDtos.size());
            }

            //状态
            if(PartySurveyConstants.MarkStatus.UN_PUBLISH.getStatus().equals(dto.getStatus())){
                dto.setPartySurveyStatus(PartySurveyConstants.PartySurveyStatus.UN_PUBLISH.getStatus());
            }else if(PartySurveyConstants.MarkStatus.PUBLISHED.getStatus().equals(dto.getStatus())){
                Date now = new Date();

                if(now.before(dto.getStartTime())){
                    dto.setPartySurveyStatus(PartySurveyConstants.PartySurveyStatus.NOT_START.getStatus());
                }else if(now.after(dto.getEndTime())){
                    //如果当前时间在结束时间之后
                    dto.setPartySurveyStatus(PartySurveyConstants.PartySurveyStatus.ENDED.getStatus());
                }else{
                    dto.setPartySurveyStatus(PartySurveyConstants.PartySurveyStatus.IN_PROGRESS.getStatus());
                }

            }else if(PartySurveyConstants.MarkStatus.CANCELED.getStatus().equals(dto.getStatus())){
                dto.setPartySurveyStatus(PartySurveyConstants.PartySurveyStatus.CANCELED.getStatus());
            }

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return partySurveyDao.queryTotal(params);
    }

    @Override
    public Long save(PartySurveyDto dto) {
        PartySurveyEntity entity = CopyUtils.copyObj(dto, PartySurveyEntity.class);
        entity.setId(Snowflake.nextId());
        partySurveyDao.insert(entity);
        return entity.getId();
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.PARTY_SURVEY_LOCK + "#{#dto.id}"
            }
    )
    public void updateById(PartySurveyDto dto) {
        PartySurveyEntity entity = CopyUtils.copyObj(dto, PartySurveyEntity.class);

        partySurveyDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartySurveyDto dto) {
        PartySurveyEntity entity = CopyUtils.copyObj(dto, PartySurveyEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, partySurveyDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partySurveyDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
